/*
 *   图片列表展示（瀑布流）
 */
var $container = $('#photo-list').masonry();
// layout Masonry again after all images have loaded
$container.imagesLoaded(function () {
    $container.masonry();
});


/*
 *   右侧伸缩栏
 */
$("#sidebar-toggle").on('click', function () {
    var isShow = $("body").attr('style') != undefined ? true : false;
    var bodyWidth = $("html").width();
    if (!isShow) {
        $("body").css({
            "width": bodyWidth + "px",
            "position": "absolute"
        });
        $("body").animate({
            "right": "240px"
        });
        $("#sidebar").animate({
            "right": 0
        });
    } else {
        $("body").animate({
            "right": 0
        }, function () {
            $("body").removeAttr("style");
        });
        $("#sidebar").animate({
            "right": "-240px"
        });
    }

});

$("body").on('click', '#main, #footer', function () {
    var isShow = $("body").attr('style') != undefined ? true : false;
    var bodyWidth = $("html").width();
    if (isShow) {
        $("body").animate({
            "right": 0
        }, function () {
            $("body").removeAttr("style");
        });
        $("#sidebar").animate({
            "right": "-240px"
        });
    }
});


/*
 *   注册登录Ajax
 */
$("#register-form .btn-success").on('click', function () {
    var submitUrl = '/user/register';
    var postData = $("#register-form").serialize();

    $.ajax({
        url: submitUrl,
        data: postData,
        type: 'post',
        success: function (result) {

            if (result == 'register_success') {
                window.location.reload();
            } else {
                var html = '';
                for (var key in result) {
                    html += '<li>' + result[key][0] + '</li>';
                }
                $("#register-alert").fadeIn();
                $("#register-alert ul").html(html);

            }
        },
        error: function (error) {
            console.log(error);
        }

    });
});


$("#login-form .btn-success").on('click', function () {
    var submitUrl = '/user/login';
    var postData = $("#login-form").serialize();

    $.ajax({
        url: submitUrl,
        data: postData,
        type: 'post',
        success: function (result) {
            if (result == 'login_success') {
                window.location.reload();
            } else if (result == 'login_error') {
                $("#login-alert").fadeIn();
                $("#login-alert ul").html('<li>用户名/邮箱或密码错误！</li>');
            } else {
                var html = '';
                for (var key in result) {
                    html += '<li>' + result[key][0] + '</li>';
                }
                $("#login-alert").fadeIn();
                $("#login-alert ul").html(html);

            }
        },
        error: function (error) {
            console.log(error);
        }

    });
});

$("#forgotpassword-form .btn-success").on('click', function () {
    var submitUrl = $("#forgotpassword-form").attr('action');
    var postData = $("#forgotpassword-form").serialize();
    var submiteBtn = $(this);
    submiteBtn.attr('disabled', 'disabled');
    $.ajax({
        url: submitUrl,
        data: postData,
        type: 'post',
        success: function (result) {
            console.log(result);

            $("#forgotpassword-alert").fadeOut(function () {
                var message = '';
                if (result.error != undefined) {
                    $("#forgotpassword-alert").removeClass('alert-success').addClass('alert-danger');
                    message = result.error;
                } else {
                    $("#forgotpassword-alert").removeClass('alert-danger').addClass('alert-success');
                    message = result.success;
                }
                $("#forgotpassword-alert").fadeIn();
                $("#forgotpassword-alert ul").html('<li>' + message + '</li>');
            });
            submiteBtn.removeAttr('disabled');
        },
        error: function (error) {
            console.log(error);
        }

    });
});


$("#login").on("hidden.bs.modal", function () {
    $(this).find("form")[0].reset();
    $("#login-alert").hide();
    $("#login-alert ul").html('');
});

$("#register").on("hidden.bs.modal", function () {
    $(this).find("form")[0].reset();
    $("#register-alert").hide();
    $("#register-alert ul").html('');
});

$("#forgotpassword").on("hidden.bs.modal", function () {
    $(this).find("form")[0].reset();
    $("#forgotpassword-alert").hide();
    $("#forgotpassword-alert ul").html('');
});


/*
 *   图片上传
 */

$(function () {
    var addCount = 0;
    var formNum = 0;
    $('#uploadimage').fileupload({
        url: '/picture/upload',
        dataType: 'json',
        add: function (e, data) {
            var file = data.files[0];
            var totalFiles = data.originalFiles.length;
            $("#drag-and-drop-zone").hide();
            $("#uploader .loading-progress").show();

            if (!loadImage(
                file,
                function (img) {
                    addCount++;
                    $(".photo-reel").show();

                    var content;
                    if (!(img.src || img instanceof HTMLCanvasElement)) {
                        content = $('<span>Loading image file failed</span>');
                    } else {
                        content = $('<a href="javascript:void(0);">').append(img);
                    }

                    content.on('click', function () {
                        if (!content.attr('clicked')) {
                            loadImage(
                                file, // img or canvas element
                                function (priviewImg) {
                                    $(".photo-preview img").hide();
                                    var imgId = parseInt(Math.random() * 10000);
                                    content.attr('data-id', imgId);
                                    priviewImg.setAttribute('data-id', imgId);
                                    $(".photo-preview").append(priviewImg);
                                    content.attr('clicked', true);
                                }, {
                                    maxWidth: 800,
                                    maxHeight: 800,
                                    canvas: false
                                }
                            );
                        } else {
                            var imgPreviewId = content.attr('data-id');
                            $(".photo-preview img").hide();
                            $(".photo-preview img").each(function () {
                                if ($(this).attr('data-id') == imgPreviewId) {
                                    $(this).show();
                                }
                            });
                        }
                        $(".photo-reel li").removeClass('selected');
                        content.parent().addClass('selected');

                        $("#uploader .picture-info-edit").hide();
                        $(".photo-reel li").each(function (index) {
                            if ($(this).attr('class') == 'selected') {
                                $("#uploader .picture-info-edit").eq(index).show();
                            }
                        });



                    });

                    $(".photo-reel ul").append($('<li>').append(content));


                    laodProcess = addCount / totalFiles * 100 + '%';
                    $("#uploader .loading-progress .progress-bar").css('width', laodProcess);
                    if (laodProcess == '100%') {
                        $("#uploader .loading-progress").hide(function () {
                            $("#uploader .active-photo").show(function () {
                                $("#uploader .photo-reel a").eq(0).trigger('click');
                            });
                        });
                    }

                    // form clone
                    loadImage.parseMetaData(file, function (exifData) {
                        formNum++;
                        var formElement = $("#templete form.picture-info-edit").clone();
                        var formElementObject = $(formElement);
                        formElement[0].id = 'C-' + formNum;
                        data.formId = 'C-' + formNum;

                        if (exifData.exif) {
                            data.exifData = exifData.exif.getAll();
                            formElementObject.find('#photo-camera').text(data.exifData.Model);
                            formElementObject.find('#photo-lens').text(data.exifData.LensModel);
                            formElementObject.find('#photo-focal_length').text(data.exifData.FocalLength);
                            formElementObject.find('#photo-shutter_speed').text(data.exifData.ShutterSpeedValue);
                            formElementObject.find('#photo-aperture').text(data.exifData.FNumber);
                            formElementObject.find('#photo-iso').text(data.exifData.PhotographicSensitivity);
                            formElementObject.find('#photo-taken_at').text(data.exifData.DateTimeOriginal);
                        }

                        formElementObject.find('#photo-name').val(file.name);

                        if (addCount == 1) {
                            formElementObject.attr('style', '');
                        }

                        $("#uploader .edit-container").append(formElementObject);
                    });
                }, {
                    maxWidth: 100,
                    maxHeight: 100,
                    canvas: true
                }
            )) {
                result.children().replaceWith(
                    $('<span>Your browser does not support the URL or FileReader API.</span>')
                );
            }

            $('.photo-actions .btn-info').on('click', function () {
                var formData = $('.edit-container form#' + data.formId).serializeArray();
                formData.push({
                    "name": "exifData",
                    "value": JSON.stringify(data.exifData)
                });
                data.formData = formData;
                data.submit();
            });

        },
        done: function (e, data) {},
        start: function (e) {
            $(".active-photo").fadeOut(function () {
                $(".finish-progress").fadeIn();
            })

        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            console.log(data);
            $('.finish-progress .progress-bar').css(
                'width',
                progress + '%'
            );

            if (data.loaded == data.total) {
                setTimeout(function () {
                    window.location = '/picture/manager';
                }, 3000);

            }
        }
    });



});


//同步上传图片信息
$(".edit-container").on('click', '.syncUploadInfo', function () {
    var thisForm = $(this).parents("form");
    var formTitle = thisForm.find("input[name='name']").val();
    var formCategory = thisForm.find("select[name='category']").val();
    var formDescription = thisForm.find("textarea[name='description']").val();
    var formLicenseType = thisForm.find("select[name='license_type']").val();
    var formTags = thisForm.find("input[name='tags']").val();

    $(".edit-container").find("input[name='name']").val(formTitle);
    $(".edit-container").find("select[name='category']").val(formCategory);
    $(".edit-container").find("textarea[name='description']").val(formDescription);
    $(".edit-container").find("select[name='license_type']").val(formLicenseType);
    $(".edit-container").find("input[name='tags']").val(formTags);

});

//标签逗号转换
$(".edit-container").on('blur', 'input[name=\'tags\']', function () {
    var replaceStr = $(this).val();
    re = new RegExp('，', 'g');
    re2 = new RegExp(',,', 'g');
    replaceStr = replaceStr.replace(re, ',');
    while (replaceStr.indexOf(',,') != -1) {
        replaceStr = replaceStr.replace(re2, ',');
    }
    if (replaceStr.lastIndexOf(',') == replaceStr.length - 1) {
        replaceStr = replaceStr.substr(0, replaceStr.length - 1);
    }
    if (replaceStr.indexOf(',') == 0) {
        replaceStr = replaceStr.substr(1, replaceStr.length);
    }



    $(this).val(replaceStr);
});

//定价

$("body").on('change', '#price-change select', function () {
    var price = $(this).val();
    var priceInput = $('#price-change').find('input[name=\'price\']');
    if (price == 100) {
        priceInput.focus();

    }
    priceInput.val(price);
});


$("body").on('keyup', '#price-change input', function () {
    var price = $(this).val();
    var priceSelect = $('#price-change').find('select');
    if (price == 0 || price == 30 || price == 60 || price == 90) {
        priceSelect.val(price);
    } else {
        priceSelect.val(100);
    }
});



//图片预览

$("#photo-modal").on("hidden.bs.modal", function () {
    $(this).removeData("bs.modal");
});

$("#photo-modal").on("click", ".detail-actions .btn-success", function () {
	if($(this).attr('data-target') === '#login') {
		$("#photo-modal").modal('hide')
		return;
	}
    var pictureId = $(this).attr('data-picture');
    var postData = {
        "picture_id": pictureId
    };
    $.ajax({
        type: 'post',
        url: '/shoppingcart/add',
        data: postData,
        success: function (result) {
            $('#photo-modal').modal('hide');
            if (result.status) {
                alert(result.message);
                $("#user-info .cart-num").text(result.count);
            } else {
                alert(result.message);
            }
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        }
    });
});

$('#photo-list .action-btn a').tooltip();




//选片台相关
$('.bs-project-modal-sm').on('hidden.bs.modal', function (e) {
    $(this).removeData("bs.modal");
})

$(".bs-project-modal-sm").on('submit', 'form', function () {
    var postData = $(this).serialize();
    var postUrl = $(this).attr('action');

    $.ajax({
        url: postUrl,
        type: 'post',
        data: postData,
        success: function (result) {
            console.log(result);
            if (result.success && result.success != undefined) {
                $('.bs-project-modal-sm').modal('hide');
                alert(result.success);
            }

            if (result.error && result.error != undefined) {
                alert(result.error);
            }
        },
        error: function (error) {
            console.log(error);
        },
        dataType: 'json'
    });

    return false;
});



//专题相关
$("#topic-modal").on("hidden.bs.modal", function () {
    $(this).removeData("bs.modal");
});

$("#photo-modal").on('click', '.topic-edit-pictures li', function () {
    $(this).find('input').trigger('click');
});

$("#picture-edit-modal").on("hidden.bs.modal", function () {
    $(this).removeData("bs.modal");
});



//编辑用户头像

$(function () {
    $("#avatar-file").fileupload({
        url: '/user/avatar',
        add: function (e, data) {

            var file = data.files[0];
            var filetypes = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
            var fileType = file.name.substring(file.name.length - 3, file.name.length);
            if ($.inArray(fileType, filetypes) == -1) {
                alert('头像文件格式必须是: ' + filetypes.join(',') + '。');
                return;
            }


            loadImage(file, function (img) {
                $(".avatar-edit i, .avatar-edit img").remove();
                $(".avatar-edit").append(img);
            }, {
                maxWidth: 80,
                maxHeight: 80
            });

            data.submit();

        },
        done: function (e, data) {

            if (data.result.success != undefined && data.result.success != "") {
                console.log(data);
            } else {
                alert(data.result.error);
            }

        }
    });
});


// 幻灯片功能
$(function() {
	var timer, autoPlayTimer;

	$("#showcase .small-item li").each(function(index) {
		$(this).on('mouseover', function() {
			timer = setTimeout(function() {
				$("#showcase .large-item li").hide().removeClass('active');
				$("#showcase .large-item li").eq(index).fadeIn().addClass('active');
			}, 1000);
		});

		$(this).on('mouseout', function() {
			clearTimeout(timer);
		});
	});

	$("#showcase").hover(function() {
		clearInterval(autoPlayTimer);
	}, function() {
		autoPlayTimer = setInterval(autoPlaySlideshow, 2000);
	});

	autoPlayTimer = setInterval(autoPlaySlideshow, 2000);

	function autoPlaySlideshow() {
		var activeIndex = 0,
			largeItem = $("#showcase .large-item li");
		$("#showcase .large-item li").each(function(index) {
			if($(this).hasClass('active')) {
				activeIndex = index;
			}
		});

		largeItem.eq(activeIndex).removeClass('active').hide();

		if(largeItem.eq(activeIndex).next().length) {
			largeItem.eq(activeIndex).next().addClass('active').fadeIn();
		} else {
			largeItem.eq(0).addClass('active').fadeIn();
		}

	}
});


// 管理员编辑用户信息

$("#user-edit-modal").on("hidden.bs.modal", function () {
    $(this).removeData("bs.modal");
});



// 选片台详情图片放大
$(function() {
	var speed = 1000,
		timer;
	$("#project-info-modal").on('mouseover', '.pictures-list img', function() {
		var imgSrc = $(this).attr('src');
		$("#project-info-modal .preview img").attr('src', imgSrc);
		$("#project-info-modal .preview").removeClass('hide');
		$("#project-info-modal .preview").fadeIn();

		clearTimeout(timer);

	}).on('mouseout', '.pictures-list img', function() {
		timer = setTimeout(function() {
			$("#project-info-modal .preview").fadeOut();
		}, speed);
	});

	$("#project-info-modal").on('mouseout', '.preview', function() {
		timer = setTimeout(function() {
			$("#project-info-modal .preview").fadeOut();
		}, speed);
	});

	$("#project-info-modal").on('mouseover', '.preview', function() {
		clearTimeout(timer);
	});

});

// 选片台详情，选中图片下载。
$(function() {
	$("#project-info-modal").on('click', '.pictures-list img', function() {
		if($(this).hasClass('active')) {
			$(this).removeClass('active');
		} else {
			$(this).addClass('active');
		}

	});
});


